const mysql = require('mysql2/promise');

/**
 * 检查数据库中的外键约束
 */
async function checkForeignKeys() {
    console.log('🔍 检查数据库中的外键约束...');

    const connection = await mysql.createConnection({
        host: '43.143.253.188',
        port: 3306,
        user: 'nextjs',
        password: 'yEAiRE2jcxTyRBy5',
        database: 'nextjs',
        timezone: '+08:00'
    });

    try {
        // 查询所有外键约束
        const [constraints] = await connection.execute(`
      SELECT 
        CONSTRAINT_NAME,
        TABLE_NAME,
        COLUMN_NAME,
        REFERENCED_TABLE_NAME,
        REFERENCED_COLUMN_NAME
      FROM 
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
      WHERE 
        REFERENCED_TABLE_SCHEMA = 'nextjs' 
        AND REFERENCED_TABLE_NAME IS NOT NULL
      ORDER BY CONSTRAINT_NAME
    `);

        console.log(`📋 找到 ${constraints.length} 个外键约束:`);

        // 按约束名称分组，找出重复的
        const constraintGroups = {};
        constraints.forEach(constraint => {
            const name = constraint.CONSTRAINT_NAME;
            if (!constraintGroups[name]) {
                constraintGroups[name] = [];
            }
            constraintGroups[name].push(constraint);
        });

        // 找出重复的约束名称
        const duplicateConstraints = Object.entries(constraintGroups)
            .filter(([name, constraints]) => constraints.length > 1);

        if (duplicateConstraints.length > 0) {
            console.log(`\n⚠️ 发现 ${duplicateConstraints.length} 个重复的外键约束名称:`);
            duplicateConstraints.forEach(([name, constraints]) => {
                console.log(`\n🔴 重复约束名称: ${name}`);
                constraints.forEach((constraint, index) => {
                    console.log(`   ${index + 1}. 表: ${constraint.TABLE_NAME}, 列: ${constraint.COLUMN_NAME} -> ${constraint.REFERENCED_TABLE_NAME}.${constraint.REFERENCED_COLUMN_NAME}`);
                });
            });
        } else {
            console.log('\n✅ 没有发现重复的外键约束名称');
        }

        // 显示所有约束
        console.log('\n📋 所有外键约束:');
        constraints.forEach((constraint, index) => {
            console.log(`   ${index + 1}. ${constraint.CONSTRAINT_NAME}: ${constraint.TABLE_NAME}.${constraint.COLUMN_NAME} -> ${constraint.REFERENCED_TABLE_NAME}.${constraint.REFERENCED_COLUMN_NAME}`);
        });

    } catch (error) {
        console.error('❌ 检查外键约束失败:', error.message);
        throw error;
    } finally {
        await connection.end();
    }
}

// 执行检查
checkForeignKeys()
    .then(() => {
        console.log('✅ 外键约束检查完成');
        process.exit(0);
    })
    .catch((error) => {
        console.error('💥 外键约束检查失败:', error.message);
        process.exit(1);
    });
